package com.lagou.work.handler;

import com.lagou.work.RpcRequest;
import com.lagou.work.service.UserServiceImpl;
import com.lagou.work.utils.SpringContextUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.lang.reflect.Method;

public class UserServerHandler extends ChannelInboundHandlerAdapter {

    // 当客户端读取数据时，该方法会被调用
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        /*UserServiceImpl userService = new UserServiceImpl();
        String result = userService.sayHallow(msg.toString());
        //服务器写入数据，将结果返回给客户端
        ctx.writeAndFlush(result);*/

        // 将读到的msg对象，强转成RpcRequest对象
        RpcRequest rpcRequest = (RpcRequest) msg;

        // 加载class文件
        Class<?> aClass = Class.forName(rpcRequest.getClassName());
        // 通过class获取服务器spring容器中service类的实例化bean对象
        Object bean = SpringContextUtil.getBean(aClass);
        Method method = aClass.getMethod(rpcRequest.getMethodName(), rpcRequest.getParameterTypes());
        method.invoke(bean, rpcRequest.getParameters());

        //服务器写入数据，将结果返回给客户端
        ctx.writeAndFlush("success");
    }

}
